<!-- eslint-disable eqeqeq -->
<template>
  <div class="app-container">

    <el-row>
      <el-select v-model="query.time" placeholder="请选择" style="width: 80px" @change="changeSelect">
        <el-option v-for="item in [
          {
            label: '出院',
            value: 'cysj_l'
          },
          {
            label: '入院',
            value: 'rysj_l'
          },
          {
            label: '结算',
            value: 'jsrq_l'
          },
          {
            label: '上传',
            value: 'lasttime'
          }
        ]" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-date-picker v-model="query.stime" value-format="yyyy-MM-dd" type="date" placeholder="开始日期"
        style="margin-left: 5px">
      </el-date-picker>
      <span style="margin-left: 2px">至</span>
      <el-date-picker v-model="query.etime" value-format="yyyy-MM-dd" type="date" placeholder="结束日期"
        style="margin-left: 5px">
      </el-date-picker>

      <el-select style="margin-left: 5px; width: 150px" v-model="query.ylfkfs" multiple collapse-tags filterable
        placeholder="医疗付款方式">
        <el-option v-for="item in ykfs" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-select v-model="query.grpsta" style="margin-left: 5px; width: 120px" placeholder="入组状态" collapse-tags
        filterable>
        <el-option-group v-for="group in 状态Ls" :key="group.label" :label="group.label">
          <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-option-group>
      </el-select>
      <el-select v-model="query.cykb" style="margin-left: 5px; width: 120px" placeholder="出院科别" collapse-tags filterable>
        <el-option v-for="item in cykbs" :key="item" :label="item" :value="item">
        </el-option>
      </el-select>
      <el-input size="medium" placeholder="病案号、姓名、出院科室、住院医师、病组编码、病组名称、入组类别" suffix-icon="el-icon-search"
        style="width: 250px; margin-left: 5px" v-model="query.s" @keyup.enter.native="search"></el-input>

      <el-button style="margin-left: 5px" type="primary" round @click="search">查询</el-button>

      <el-dropdown style="margin-left: 5px" @command="handleCommand">
        <el-button type="primary" :loading="commandProcess">
          操作<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="exportExcel">导出EXCEL</el-dropdown-item>
          <el-dropdown-item command="importExcel">导入数据</el-dropdown-item>
          <el-dropdown-item command="donwloadTpl">下载模板</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <input type="file" id="fileUpload"
        accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        @change="readExce" style="display: none" />
    </el-row>

    <!-- 表格 -->
    <el-row>
      <el-table ref="table" :data="ls" style="width: 100%" v-loading="loading" :row-class-name="rowClass" height="600"
        highlight-current-row @sort-change="sortChange" stripe>
        <el-table-column prop="bah" width="150" fixed label="病案号">
        </el-table-column>
        <el-table-column prop="xm" fixed label="姓名"> </el-table-column>
        <el-table-column prop="ylfkfs_str" fixed label="付款方式" width="180">
        </el-table-column>
        <el-table-column prop="xb_str" label="性别"> </el-table-column>
        <el-table-column prop="nl" label="年龄"> </el-table-column>
        <el-table-column prop="sjzyts" label="住院天数" width="120">
        </el-table-column>
        <el-table-column prop="mdc" :sortable="true" label="MDC">
        </el-table-column>
        <el-table-column prop="drg" :sortable="true" label="病组编码" width="120">
        </el-table-column>
        <el-table-column prop="drgName" label="病组名称" width="300">
        </el-table-column>
        <el-table-column prop="weight" width="120" :sortable="true" label="标准点数">
        </el-table-column>
        <el-table-column width="120" prop="病例点数" label="病例点数">
          <template slot-scope="scope">
            {{ 病例点数fmt(scope.row) }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="benchmarkStayDays" :sortable="true" label="标准床日" width="120">
        </el-table-column> -->
        <el-table-column prop="benchmarkFee" :sortable="true" label="标准费用" width="120">
          <template slot-scope="scope">
            {{ (scope.row.benchmarkFee || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="zfy" :sortable="true" label="住院费" width="120">
        </el-table-column>
        <el-table-column label="费用差" prop="费用差" :formatter="费用差fmt" width="120">
        </el-table-column>
        <!-- 新增字段  保留两位小数-->
        <el-table-column prop="jjzfze" label="基金支付总额" width="120">
          <template slot-scope="scope">
            {{ (scope.row.jjzfze || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="grzhzf" label="个人账户支付" width="120">
        </el-table-column>
        <el-table-column prop="grzf" label="个人自付" width="120">
        </el-table-column>
        <el-table-column prop="DRG统筹" label="DRG统筹" :formatter="DRG统筹fmt" width="120">
        </el-table-column>
        <el-table-column prop="标准费用比" label="标准费用比" :formatter="标准费用比" width="120">
        </el-table-column>

        <el-table-column prop="rzlb" label="入组类别"> </el-table-column>
        <el-table-column prop="高低倍率" label="高低倍率" :formatter="高低倍率">
        </el-table-column>
        <el-table-column prop="nogrpmsg" label="未入组原因" width="150">
        </el-table-column>
        <el-table-column prop="qccount" label="质控异常数" width="150">
          <template slot-scope="scope">
            {{ scope.row.qccount == 0 ? "-" : scope.row.qccount }}
          </template>
        </el-table-column>
        <el-table-column prop="cykb" label="出院科室" :sortable="true" width="150">
        </el-table-column>
        <el-table-column prop="zyys" label="住院医师" width="150">
        </el-table-column>
        <el-table-column prop="rysj_l" label="入院时间" :sortable="true" width="100">
        </el-table-column>
        <el-table-column prop="cysj_l" label="出院时间" :sortable="true" width="100">
        </el-table-column>
        <el-table-column prop="jbdm" label="主诊断编码" width="120">
        </el-table-column>
        <el-table-column prop="zyzd" label="主诊断名称" width="200">
        </el-table-column>
        <el-table-column prop="ssjczbm1" label="主手术编码" width="120">
        </el-table-column>
        <el-table-column prop="ssjczmc1" label="主手术名称" width="200">
        </el-table-column>
        <el-table-column prop="zfje" :sortable="true" label="自付金额" width="120">
        </el-table-column>
        <el-table-column prop="lasttime" :sortable="true" label="上传时间" width="150"></el-table-column>



        <el-table-column prop="dead_str" label="是否死亡" width="100">
          <!-- <template slot-scope="scope">
            {{ scope.row.dead ? "是" : "否" }}
          </template> -->
        </el-table-column>
        <!-- <el-table-column prop="error" label="数据异常"> </el-table-column> -->
        <el-table-column fixed="right" label="" width="80">
          <template slot-scope="scope">
            <el-button @click="handleRowClick(scope.row)" type="text" size="small">查看</el-button>
            <!-- <el-button
              @click="handleRowRefresh(scope.row)"
              type="text"
              size="small"
              >刷新</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <!-- 分页 -->
    <el-row>
      <pagination v-show="query.totalElements > 0" :total="query.totalElements" :page.sync="query.page"
        :limit.sync="query.size" @pagination="loadBanInfo" />
    </el-row>

    <el-row>
      <el-dialog title="病人详情" :visible.sync="dialogVisible" width="50%">
        <el-tabs v-model="activeName">
          <el-tab-pane label="基本信息" name="baseInfo">
            <el-descriptions title="">
              <el-descriptions-item label="病案号">{{
                curRow.bah
              }}</el-descriptions-item>
              <el-descriptions-item label="姓名">{{
                curRow.xm
              }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{
                curRow.xb_str
              }}</el-descriptions-item>
              <el-descriptions-item label="健康卡号">
                {{ curRow.jkkh }}
              </el-descriptions-item>

              <el-descriptions-item label="出生日期">{{
                curRow.csrq
              }}</el-descriptions-item>
              <el-descriptions-item label="年龄">{{
                curRow.nl
              }}</el-descriptions-item>
              <el-descriptions-item label="国籍">{{
                curRow.gj
              }}</el-descriptions-item>
              <el-descriptions-item label="(年龄不足1周岁的)年龄(月)">{{
                curRow.bzyzsnl
              }}</el-descriptions-item>

              <el-descriptions-item label="新生儿出生体重(克)">{{
                curRow.xsecstz
              }}</el-descriptions-item>

              <el-descriptions-item label="新生儿入院体重(克）">{{
                curRow.xserytz
              }}</el-descriptions-item>

              <el-descriptions-item label="出生地">{{
                curRow.csd
              }}</el-descriptions-item>
              <el-descriptions-item label="籍贯">{{
                curRow.gg
              }}</el-descriptions-item>
              <el-descriptions-item label="民族">{{
                curRow.mz
              }}</el-descriptions-item>

              <el-descriptions-item label="身份证号">{{
                curRow.sfzh
              }}</el-descriptions-item>

              <el-descriptions-item label="职业">{{
                curRow.zy
              }}</el-descriptions-item>

              <el-descriptions-item label="婚姻">{{
                curRow.hy
              }}</el-descriptions-item>

              <el-descriptions-item label="现住址">{{
                curRow.xzz
              }}</el-descriptions-item>
              <el-descriptions-item label="电话">{{
                curRow.dh
              }}</el-descriptions-item>

              <el-descriptions-item label="邮编">{{
                curRow.yb1
              }}</el-descriptions-item>

              <el-descriptions-item label="户口地址">{{
                curRow.hkdz
              }}</el-descriptions-item>

              <el-descriptions-item label="邮编">{{
                curRow.yb2
              }}</el-descriptions-item>

              <el-descriptions-item label="工作单位及地址">{{
                curRow.gzdwjdz
              }}</el-descriptions-item>

              <el-descriptions-item label="单位电话">{{
                curRow.dwdh
              }}</el-descriptions-item>

              <el-descriptions-item label="邮编">{{
                curRow.yb3
              }}</el-descriptions-item>

              <el-descriptions-item label="联系人姓名">{{
                curRow.lxrxm
              }}</el-descriptions-item>

              <el-descriptions-item label="关系">{{
                curRow.gx
              }}</el-descriptions-item>

              <!-- 地址由cz修改为dz -->
              <el-descriptions-item label="地址">{{
                curRow.dz
              }}</el-descriptions-item>

              <el-descriptions-item label="电话">{{
                curRow.dh2
              }}</el-descriptions-item>

              <el-descriptions-item label="错误消息">{{
                curRow.error
              }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          <el-tab-pane label="住院信息" name="zyqk">
            <el-descriptions title="">
              <el-descriptions-item label="入院途径">
                {{ curRow.rytj }}
              </el-descriptions-item>

              <el-descriptions-item label="入院时间">
                {{ curRow.rysj }} {{ curRow.rysjs }}
              </el-descriptions-item>

              <el-descriptions-item label="入院科别">
                {{ curRow.rykb }}
              </el-descriptions-item>

              <el-descriptions-item label="入院病房">
                {{ curRow.rybf }}
              </el-descriptions-item>

              <el-descriptions-item label="转科科别">
                {{ curRow.zkkb }}
              </el-descriptions-item>

              <el-descriptions-item label="住院次数">
                {{ curRow.zycs }}
              </el-descriptions-item>

              <el-descriptions-item label="出院时间">
                {{ curRow.cysj }} {{ curRow.cysjs }}
              </el-descriptions-item>

              <el-descriptions-item label="出院科别">
                {{ curRow.cykb }}
              </el-descriptions-item>

              <el-descriptions-item label="出院病房">
                {{ curRow.cybf }}
              </el-descriptions-item>

              <el-descriptions-item label="实际住院(天)">
                {{ curRow.sjzyts }}
              </el-descriptions-item>

              <el-descriptions-item label="病人来源">
                {{ curRow.brly }}
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          <el-tab-pane label="病案首页" name="third">
            <el-descriptions title="">
              <el-descriptions-item label="门诊诊断编码">{{
                curRow.jbbm
              }}</el-descriptions-item>

              <el-descriptions-item label="门诊诊断名称">{{
                curRow.mzzd
              }}</el-descriptions-item>

              <el-descriptions-item label="实施临床路径">{{
                curRow.sslclj
              }}</el-descriptions-item>

              <el-descriptions-item label="抢救次数">{{
                curRow.qjcs
              }}</el-descriptions-item>

              <el-descriptions-item label="抢救成功次数">{{
                curRow.qjcgcs
              }}</el-descriptions-item>

              <el-descriptions-item label="确诊日期">{{
                curRow.qzrq
              }}</el-descriptions-item>

              <el-descriptions-item label="是否择期手术">{{
                curRow.zqss
              }}</el-descriptions-item>

              <el-descriptions-item label="疾病编码(首页)">{{
                curRow.h23
              }}</el-descriptions-item>

              <el-descriptions-item label="中毒的外部原因(首页)">{{
                curRow.wbyy
              }}</el-descriptions-item>

              <el-descriptions-item label="疾病编码(首页)">{{
                curRow.jbmm
              }}</el-descriptions-item>

              <el-descriptions-item label="病理号">{{
                curRow.blh
              }}</el-descriptions-item>

              <el-descriptions-item label="病理诊断(首页)">{{
                curRow.blzd
              }}</el-descriptions-item>

              <el-descriptions-item label="药物过敏">{{ curRow.ywgm }}
                <el-tag size="small"> 1无 2有</el-tag>
              </el-descriptions-item>

              <el-descriptions-item label="过敏药物疾病">{{
                curRow.gmyw
              }}</el-descriptions-item>

              <el-descriptions-item label="死亡患者尸检">{{
                curRow.swhzsj
              }}</el-descriptions-item>

              <el-descriptions-item label="血型">{{
                curRow.xx
              }}</el-descriptions-item>

              <el-descriptions-item label="Rh">{{
                curRow.rh
              }}</el-descriptions-item>

              <el-descriptions-item label="主任（副主任）医师">{{
                curRow.zrys
              }}</el-descriptions-item>

              <el-descriptions-item label="主治医师">{{
                curRow.zzys
              }}</el-descriptions-item>

              <el-descriptions-item label="住院医师">{{
                curRow.zyys
              }}</el-descriptions-item>

              <el-descriptions-item label="责任护士">{{
                curRow.zrhs
              }}</el-descriptions-item>

              <el-descriptions-item label="进修医师">{{
                curRow.jxys
              }}</el-descriptions-item>

              <el-descriptions-item label="实习医师">{{
                curRow.sxys
              }}</el-descriptions-item>

              <el-descriptions-item label="编码员">{{
                curRow.bmy
              }}</el-descriptions-item>

              <el-descriptions-item label="病案质量">{{
                curRow.bazl
              }}</el-descriptions-item>

              <el-descriptions-item label="质控医师">{{
                curRow.zkys
              }}</el-descriptions-item>

              <el-descriptions-item label="质控护士">{{
                curRow.zkhs
              }}</el-descriptions-item>

              <el-descriptions-item label="质控日期">{{
                curRow.zkrq
              }}</el-descriptions-item>

              <el-descriptions-item label="离院方式">{{
                curRow.lyfs
              }}</el-descriptions-item>

              <el-descriptions-item label="医嘱转院，拟接收医疗机构名称">{{
                curRow.yzzy_yljg
              }}</el-descriptions-item>

              <el-descriptions-item label="医嘱转社区卫生服务机构/乡镇卫生院，拟接收医疗机构名称">{{ curRow.wsy_yljg }}</el-descriptions-item>

              <el-descriptions-item label="是否有出院31天内再住院计划">{{
                curRow.sfzzyjh
              }}</el-descriptions-item>

              <el-descriptions-item label="目的">{{
                curRow.md
              }}</el-descriptions-item>

              <el-descriptions-item label="颅脑损伤患者昏迷入院前时间：天">{{
                curRow.ryq_t
              }}</el-descriptions-item>

              <el-descriptions-item label="颅脑损伤患者昏迷入院前时间：小时">{{
                curRow.ryq_xs
              }}</el-descriptions-item>

              <el-descriptions-item label="颅脑损伤患者昏迷入院前时间：分">{{
                curRow.ryq_f
              }}</el-descriptions-item>

              <el-descriptions-item label="颅脑损伤患者昏迷入院后时间：天">{{
                curRow.ryh_t
              }}</el-descriptions-item>

              <el-descriptions-item label="颅脑损伤患者昏迷入院后时间：小时">{{
                curRow.ryh_xs
              }}</el-descriptions-item>

              <el-descriptions-item label="颅脑损伤患者昏迷入院后时间：分">{{
                curRow.ryh_f
              }}</el-descriptions-item>

              <el-descriptions-item label="重症监护室名称">{{
                curRow.zzjhmc
              }}</el-descriptions-item>

              <el-descriptions-item label="重症监护的开始时间">{{
                curRow.zzjhkssj
              }}</el-descriptions-item>

              <el-descriptions-item label="重症监护的结束时间">{{
                curRow.zzjhjssj
              }}</el-descriptions-item>

              <el-descriptions-item label="入院病情(首页)">{{
                curRow.rybq
              }}</el-descriptions-item>
              <el-descriptions-item label="出院情况(首页)">{{
                curRow.cyqk
              }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          <el-tab-pane label="出院诊断及手术操作" name="fourth">
            <el-table :data="curRow.zdLs" border style="width: 100%">
              <el-table-column align="center" prop="c" label="类型" width="100">
              </el-table-column>
              <el-table-column align="center" prop="code" label="编码">
              </el-table-column>
              <el-table-column align="center" prop="name" label="名称">
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="质控详情" name="qc">
            <el-table :data="curRow.qcs" border style="width: 100%">
              <el-table-column align="center" prop="n" label="字段名">
              </el-table-column>
              <el-table-column align="center" prop="f" label="字段">
              </el-table-column>
              <el-table-column align="center" prop="t" label="异常类别">
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </el-dialog>
    </el-row>

  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { UserModule } from '@/store/modules/user'
import { InfoLs, getKeysByCompany } from '@/api/cloudwebapi'
import Pagination from '@/components/Pagination/index.vue'
import { cloneDeep } from 'lodash'
import { Form, Table } from 'element-ui'
import { parseTime, dateFormat, formatJson } from '@/utils'
import { dicList, refreshData, uploadData } from '@/api/datatranform'
import { exportJson2Excel } from '@/utils/excel'
import XLSX from 'xlsx'

@Component({
  name: 'HospBanInfo',
  components: {
    Pagination
  }
})
export default class extends Vue {
  private query = {
    s: '',
    page: 1,
    size: 10,
    stime: '',
    etime: dateFormat(new Date(), 'yyyy-MM-dd'),
    time: 'jsrq_l', // cysj_l rysj_l jsrq_l lasttime
    order: 'descending',
    orderProp: 'jsrq_l',
    totalElements: 0,
    ylfkfs: '',
    grpsta: '',
    zyys: ''
  };

  // 选择查询时间类型的change事件
  changeSelect(option: any) {
    // console.log(option);
    this.query.orderProp = option
  }

  private 费用差fmt(row: any) {
    // 修改：DRG统筹 - 基金支付总额
    // console.log('rdrg', row.drgtc, row.jjzfze)
    // row['费用差'] = (row.drgtc - row.jjzfze).toFixed(2)
    if (row.drgtc && row.jjzfze) {
      row['费用差'] = (row.drgtc - row.jjzfze).toFixed(2)
    } else {
      row['费用差'] = ''
    }

    return row['费用差']
  }

  // 新增
  private 标准费用比(row: any) {
    // console.log(row.zfy, row.benchmarkFee)
    // 总费用/标准费用
    if (row.zfy && row.benchmarkFee) {
      row['标准费用比'] = (row.zfy / row.benchmarkFee).toFixed(2)
    } else {
      row['标准费用比'] = ''
    }
    return row['标准费用比']
  }

  // DRG统筹格式化  保留两位小数
  private DRG统筹fmt(row: any) {
    if (row.drgtc) {
      row['DRG统筹'] = row.drgtc.toFixed(2)
    } else {
      row['DRG统筹'] = ''
    }
    return row['DRG统筹']
  }

  private 状态Ls = [
    {
      label: '入组状态',
      options: [
        {
          label: '已入组',
          value: '已入组',
          wh: { f: 'ingrp', op: 'eq', vals: true }
        },
        {
          label: '未入组',
          value: '未入组',
          wh: { f: 'ingrp', op: 'eq', vals: false }
        }
      ]
    },
    {
      label: '未入组状态',
      options: [
        {
          label: '0000组',
          value: '0000组',
          wh: { f: 'zreogrp', op: 'eq', vals: 1 }
        },
        {
          label: 'QY组',
          value: 'QY组',
          wh: { f: 'qygrp', op: 'eq', vals: 1 }
        }
      ]
    },
    {
      label: '高低倍率',
      options: [
        {
          label: '高倍率',
          value: '高倍率',
          wh: { f: 'gdbl', op: 'eq', vals: 1 }
        },
        {
          label: '正常',
          value: '正常',
          wh: { f: 'gdbl', op: 'eq', vals: 0 }
        },
        {
          label: '低倍率',
          value: '低倍率',
          wh: { f: 'gdbl', op: 'eq', vals: -1 }
        }
      ]
    },
    {
      label: '质控',
      options: [
        {
          label: '质控异常',
          value: '质控异常',
          wh: { f: 'qc', op: 'eq', vals: true }
        }
      ]
    }
  ];

  private loading = true;

  private ls: Array<any> = [];

  private activeName = 'baseInfo';
  private rowClass(r: any) {
    const { row } = r
    if (row.iserror) {
      return 'error'
    }
    return ''
  }

  private commandProcess = false;

  // 上传excel
  private readExce(e: any) {
    const fileReader = new FileReader()
    const files = e.target.files
    if (files.length === 0) return

    fileReader.onload = async (ev: any) => {
      const loading = this.$loading({ text: '正在上传....' })
      let ls: Array<any> = []
      try {
        try {
          const data = ev.target.result
          var workbook = XLSX.read(data, {
            type: 'binary'
          }) // 以二进制流方式读取得到整份excel表格对象
        } catch (e) {
          this.$message('文件类型不正确')
          return
        }
        // 表格的表格范围，可用于判断表头是否数量是否正确
        let fromTo: any = ''
        // 遍历每张表读取
        for (const sheet in workbook.Sheets) {
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            fromTo = workbook.Sheets[sheet]['!ref']
            ls = ls.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]))
            // break; // 如果只取第一张表，就取消注释这行
          }
        }
        const d: any = await uploadData(ls)
        this.$confirm(`操作状态：${d.msg}`, '系统提示', {
          showCancelButton: false,
          type: 'success'
        }).then((v) => {
          this.search()
        })
      } finally {
        loading.close()
        e.target.value = ''
      }
      // 在控制台打印出来表格中的数据
    }
    // 以二进制方式打开文件
    fileReader.readAsBinaryString(files[0])
  }

  private handleCommand(cmd: any) {
    this.commandProcess = true
    switch (cmd) {
      case 'exportExcel':
        this.exportExcel()
        break
      case 'donwloadTpl':
        const a = document.createElement('a')
        a.href = './static/DRG文件上传模板.xlsx'
        a.download = 'DRG文件上传模板.xlsx'
        a.style.display = 'none'
        document.body.appendChild(a)
        a.click()
        a.remove()
        break
      case 'importExcel': // 导入数据
        document.getElementById('fileUpload')?.click()
        break
    }
    this.commandProcess = false
  }

  private 高低倍率(row: any) {
    const gdbl = row.gdbl
    let s = '正常'
    if (gdbl === 1) s = '高倍率'
    if (gdbl === -1) s = '低倍率'
    row['高低倍率'] = s
    return s
  }

  // 导出EXCEL
  private exportExcel() {
    const table: any = this.$refs.table as Table
    const cols = table.columns
    // console.log(cols)
    const tHeader = cols.map((it: any) => it.label).filter((it: any) => !!it)
    const filterVal = cols
      .map((it: any) => it.property)
      .filter((it: any) => !!it) //
    const data = formatJson(filterVal, this.ls)
    const ns = [
      '病例信息',
      this.query.stime.replaceAll('-', ''),
      this.query.etime.replaceAll('-', '')
    ].join('-')
    exportJson2Excel(tHeader, data, ns)
  }

  private dialogVisible = false;
  /**
   * 查看详情
   */
  private curRow: any = {};
  private handleRowClick(row: any) {
    this.curRow = row
    const 出院诊断列表: Array<any> = [
      {
        code: row.jbdm,
        name: row.zyzd,
        c: '主诊断'
      }
    ]
    // 诊断
    for (let i = 1; i <= 15; i++) {
      const cp = `jbdm${i}`
      const np = `qtzd${i}`
      if (row[cp] && row[np]) {
        出院诊断列表.push({ code: row[cp], name: row[np] })
      }
      // else break
    }
    if (row.ssjczbm1) {
      出院诊断列表.push({
        code: row.ssjczbm1,
        name: row.ssjczmc1,
        c: '主手术'
      })
    }
    for (let i = 2; i <= 8; i++) {
      const cp = `ssjczbm${i}`
      const np = `ssjczmc${i}`
      if (row[cp] && row[np]) {
        出院诊断列表.push({ code: row[cp], name: row[np] })
      }
      // else break
    }

    this.curRow.zdLs = 出院诊断列表
    this.dialogVisible = true
  }

  private search() {
    const table: any = this.$refs.table as Table // 清除表格中排序条件
    table.clearSort()
    this.query.orderProp = this.query.time // 修改排序字段为查询时间条件
    this.query.page = 1
    this.loadBanInfo()
  }

  private async handleRowRefresh(row: any) {
    const loading = this.$loading({})
    const { data } = await refreshData([row])
    this.loadBanInfo()
    loading.close()
  }

  // 修改排序字段
  private async sortChange(p: any) {
    // console.log(p)

    const order = p.order
    let prop = p.prop
    const sortMap: any = {
      cykb: 'cykb.keyword',
      mdc: 'mdc.keyword',
      drg: 'drg.keyword'
    }

    this.query.order = order
    prop = sortMap[prop] || prop
    this.query.orderProp = prop
    this.query.page = 1

    // console.log(this.query.orderProp)
    // console.log(this.query.order)

    // 当排序字段选为null时 排序为默认 排序字段为查询时间类型
    if (this.query.order == null) {
      this.query.order = 'descending'
      this.query.orderProp = this.query.time
    }

    this.loadBanInfo()
  }

  private dicLs: Array<any> = [];
  private ykfs: Array<any> = [];

  private 差异系数s: Array<any> = [];

  private async loadDicLs() {
    const { data } = await dicList({ size: 1000 })

    return data.content
  }

  private 字典获取值(val: any, c: any) {
    const ts = this.dicLs.filter((it: any) => it.category == c && it.code == val)
    if (ts.length > 0) return ts[0].name
    return ''
  }

  private 病例点数fmt(row: any) {
    const weight = row.weight || 0
    let dfcoe = row.dfcoe || 0
    // 基础组
    if (row.dkkx == '0') {
      dfcoe = 1
    }
    row['病例点数'] = (weight * dfcoe).toFixed(2)
    return row['病例点数']

    // 医院等级系统数
    // try {
    //   let ts = this.差异系数s.filter((it: any) => it.code == row.companylevel);
    //   if (ts.length > 0) {
    //     let 差异系数 = parseFloat(ts[0].name);
    //     let n = (row.weight * 差异系数).toFixed(2);
    //     //TODO:解决导出异常
    //     row.病例点数 = n;
    //     return n;
    //   }
    // } catch (e) {}
    // return 0;
  }

  // 加载病例数据
  private async loadBanInfo() {
    this.loading = true
    const q: any = cloneDeep(this.query)

    if (q.time !== 'lasttime') {
      q.stime = q.stime.replaceAll('-', '')
      q.etime = q.etime.replaceAll('-', '')
    }

    if (q.ylfkfs) q.ylfkfs = q.ylfkfs.join(',')

    if (q.grpsta && q.grpsta.length > 0) {
      const wh = []
      // for (let o of q.grpsta) {
      //   let ts = this.状态Ls
      //     .flatMap((it: any) => it.options)
      //     .filter((it: any) => it.value == o);
      //   if (ts.length > 0) {
      //     wh.push(ts[0].wh);
      //   }
      // }
      const ts = this.状态Ls
        .flatMap((it: any) => it.options)
        .filter((it: any) => it.value == q.grpsta)
      if (ts.length > 0) {
        wh.push(ts[0].wh)
      }
      q.grpsta = JSON.stringify(wh)
    }
    // 调取病例列表数据接口
    const { data } = await InfoLs(q)
    // console.log(data.content)
    // 医疗付款方式、性别赋值
    const ts = data.content || []

    const fieldMap: any = {
      ylfkfs: '医疗付款方式代码',
      xb: '性别代码',
      zy: '职业代码',
      hy: '婚姻状况代码',
      gx: '联系人关系代码',
      rytj: '入院途径',
      rh: 'Rh',
      xx: '血型编码',
      lyfs: '离院方式'
    }
    ts.forEach((it: any) => {
      const keys = Object.keys(fieldMap)
      for (const f of keys) {
        it[`${f}_str`] = this.字典获取值(it[f], fieldMap[f])
      }
      it.dead_str = it.dead_str ? '是' : '否'
    })
    this.ls = ts

    this.query.totalElements = data.totalElements
    this.loading = false
  }

  get roles() {
    return UserModule.roles
  }

  async created() {
    const cDate = new Date()
    // cDate.setMonth(cDate.getMonth() - 3)
    cDate.setMonth(cDate.getMonth()) // 修改默认开始时间为当月1号
    cDate.setDate(1)
    this.query.stime = dateFormat(cDate, 'yyyy-MM-dd')
    this.dicLs = await this.loadDicLs()
    this.差异系数s = this.dicLs.filter(
      (it: any) => it.category == '医院等级系统数'
    )
    this.ykfs = this.dicLs
      .filter((it: any) => it.category == '医疗付款方式代码')
      .map((it: any) => ({ label: it.name, value: it.code }))
    this.loadBanInfo()
    this.loadCompany4Dept()
  }

  private cykbs: Array<any> = [];

  async loadCompany4Dept() {
    const { data } = await getKeysByCompany({
      t: dateFormat(new Date(), 'yyyyMMddhhmm'),
      k: 'cykb.keyword'
    })
    this.cykbs = data
  }
}
</script>

<style lang="scss">
.el-date-editor {
  width: 140px !important;
}

.error {
  color: red;
}

.pagination-container {
  float: right;
}

.el-dialog__body {
  padding: 10px !important;
}
</style>
